package com.dk.service.impl;

import com.dk.pojo.TSpike;
import com.dk.mapper.TSpikeMapper;
import com.dk.service.ITSpikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-10-30
 */
@Service
public class TSpikeServiceImpl extends ServiceImpl<TSpikeMapper, TSpike> implements ITSpikeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private TSpikeMapper tSpikeMapper;

    @Transactional
    @Override
    public void createOrder(Long id,String name,Long admin_id) throws Exception{

        Long id2 = (Long) redisTemplate.boundHashOps("user-buy").get(name);
        if (id2 == id){
            throw new Exception("您已抢购过了");
        }

        //根据商品 Id 查询库存
        String stockCount = (String) redisTemplate.boundValueOps(id).get();
        //判断商品是否为 null
        if (stockCount == null || Long.parseLong(stockCount) <= 0){
            throw new Exception("商品已售罄11");
        }

        //扣减库存
        Long decrement = redisTemplate.boundValueOps(id).decrement();
        //如果商品只剩最后一件  需要更新数据库 删除缓存
        if (decrement == 0){
            //根据商品id查询缓存
            TSpike tSpike = (TSpike)redisTemplate.boundHashOps("spikeGoods").get(id);
            //删除缓存 更新数据库
            tSpike.setStockCount(0);

            tSpikeMapper.updateById(tSpike);
            redisTemplate.boundHashOps("spikeGoods").delete(id);
        }

        //发送 mq 消息 异步下单
        String str = name + "," + id + "," + admin_id;
        rocketMQTemplate.convertAndSend("seckill-goods",str);

        //更新 redis 限购
        redisTemplate.boundHashOps("user-buy").put(name,id);
    }

    //修改状态 ()
    @Override
    public Integer deleInfo(Integer id, Integer status) {
        return tSpikeMapper.updateByIdDele(id,status);
    }

    //查询所有
    @Override
    public List<TSpike> getInfoAll() {
        return tSpikeMapper.selectList(null);
    }

    //
    @Override
    public Integer updateInfo(TSpike tSpike) {
        Integer integer = tSpikeMapper.updateById(tSpike);
        return integer;
    }
}
